﻿define([
    'require',
    'angular',
    'underscore'
], function (require, angular, _) {
    return function ($scope, $routeParams, $http, RuleSerivce,$dataSourceManager,$timeout,Resource,$compile,$rootScope, GillionMsg,$rootScope) {
        $scope.attributeName="属性详情";
        RuleSerivce.promises().then(function () {
            $scope.businessModelId=$rootScope.currPackage.businessModelId;

            Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
                id:  $scope.businessModelId
            }, function (response) {
                if(response.data!=null){
                    $scope.modelAttributes=response.data;
                    $timeout(function () {
                        for(var i=0;i<$scope.modelAttributes.length;i++){
                            if($scope.modelAttributes[i].dataType=='Object'){
                                $scope.viewObject($scope.modelAttributes[i].id,1,$scope.modelAttributes[i].name,$scope.modelAttributes[i].dataType,$scope.modelAttributes[i].valueType,$scope.modelAttributes[i].valueExpress,$scope.modelAttributes[i].isMust);
                            }
                        }
                    },500);

                }
            });
        });

        $scope.rightNone=true;
        $scope.rightManager=false;
        $scope.addOper=false;
        $scope.editOper=false;
        var businessModelAttributeResource = Resource("/grule-manager/businessModelAttribute/:id", {
            id: "@id"
        });

        var childAttributeResource = Resource("/grule-manager/businessModelAttribute/childList/:id", {
            id: "@id"
        });
        function refresh(){
            Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
                id:  $scope.businessModelId
            }, function (response) {
                if(response.data!=null){
                    $scope.modelAttributes=response.data;
                    angular.element(document).trigger('refresh.modelVariable');
                }
            });
        }
        $scope.addAttribute = function (){
            $scope.attributeName="增加属性";
            $scope.rightNone=false;
            $scope.rightManager=true;
            $scope.addOper=true;
            $scope.editOper=false;
            var attribute={'isMust':'false'};
            $scope.attribute = attribute;
        };

        $scope.add=function(){
            $scope.attribute.businessModelId=$scope.businessModelId;
            if($scope.attribute.valueType=='JDBC'){
                editParams("JDBC");
                $scope.attribute.dataType="String";
            } else if ($scope.attribute.valueType=='Rule') {
                editParams("Rule");
                $scope.attribute.dataType="String";
            }else if ($scope.attribute.valueType=='RemoteService') {
                editParams("RemoteService");
                $scope.attribute.dataType="String";
            }else if ($scope.attribute.valueType=='Dubbo') {
                editParams("Dubbo");
                $scope.attribute.dataType="String";
            }else if ($scope.attribute.valueType=='SpringCloud') {
                editParams("SpringCloud");
                $scope.attribute.dataType="String";
            }else if($scope.attribute.valueType=='InParameter'&&$scope.attribute.isObjectType==0){
                $scope.attribute.dataType="String";
            }else if($scope.attribute.valueType=='InParameter'&&$scope.attribute.isObjectType==1){
                $scope.attribute.dataType="Object";
            }
            if($scope.attribute.dataType=="Integer"&&(isNaN($scope.attribute.valueExpress)==true||$scope.attribute.valueExpress.match("^-?[0-9]*$")==null)){
                GillionMsg.alert("提示","请输入整型的表达式");
                return;
            }else if($scope.attribute.dataType=="Double"&&(isNaN($scope.attribute.valueExpress)==true||$scope.attribute.valueExpress.match("^[-+]?[0-9]*\.?[0-9]+$")==null)){
                GillionMsg.alert("提示","请输入浮点型的表达式");
                return;
            }else if($scope.attribute.dataType=="Date"&&$scope.attribute.valueExpress.match("^[1-2][0-9][0-9][0-9]-([1][0-2]|0[1-9])-([12][0-9]|3[01]|0[1-9]) ([01][0-9]|[2][0-3]):[0-5][0-9]:[0-5][0-9]?\\d$")==null){
                GillionMsg.alert("提示","请输入时间的表达式");
                return;
            }else if($scope.attribute.dataType=="Boolean"&&$scope.attribute.valueExpress!="true"&&$scope.attribute.valueExpress!="false"){
                GillionMsg.alert("提示","请输入布尔型的表达式");
                return;
            }
            angular.element('form[name="attributeForm"]').scope().attributeForm.verify().then(function() {
                businessModelAttributeResource.create($scope.attribute, function (response) {
                    if (response.success) {
                        $rootScope.model = false;
                        $rootScope.detailsShow = true;
                        $rootScope.promPtShow = false;
                        refresh();
                        $scope.attribute = {};
                    }
                });
            })
        };

        $scope.addSon=function(id){
            $scope.rightNone=false;
            $scope.rightManager=true;
            $scope.addOper=true;
            $scope.editOper=false;
            var attribute={"isMust":"false"};
            $scope.attribute = attribute;
            $scope.attribute.businessModelId=$scope.businessModelId;
            $scope.attribute.parentId=id;
        };

        //规则属性编辑
        function editParams(type) {
            var valueExpress;
            if(type=="JDBC"){
                valueExpress = {
                    sqlName:$scope.attribute.sqlName,
                    sqlColumn:$scope.attribute.sqlColumn,
                    params: []
                };
            }else if(type=="RemoteService"){
                valueExpress = {
                    serviceName: $scope.attribute.serviceName,
                    params: []
                };
            }else if(type=="Dubbo"){
                valueExpress = {
                    dubboName: $scope.attribute.dubboName,
                    params: []
                };
            }else if(type=="SpringCloud"){
                valueExpress = {
                    springCloudName: $scope.attribute.springCloudName,
                    params: []
                };
            }else if(type=="Rule"){
                valueExpress = {
                    groupId: $scope.attribute.groupId,
                    artifactId: $scope.attribute.artifactId,
                    params: []
                };
            }
            angular.forEach($scope.attribute.params, function(param){
                valueExpress.params.push(param.value);
            });

            $scope.attribute.valueExpress = JSON.stringify(valueExpress);
        }

        $scope.edit=function(id){
            if($scope.attribute.valueType=='JDBC'){
                editParams("JDBC");
            }else if($scope.attribute.valueType=='RemoteService'){
                editParams("RemoteService");
            }else if ($scope.attribute.valueType == 'Rule') {
                editParams("Rule");
            }else if ($scope.attribute.valueType == 'Dubbo') {
                editParams("Dubbo");
            }else if ($scope.attribute.valueType == 'SpringCloud') {
                editParams("SpringCloud");
            }else if($scope.attribute.valueType=='InParameter'){
                if($scope.attribute.dataType!="Object"){
                    $scope.attribute.dataType = "String";
                }
            }
            if($scope.attribute.dataType=="Integer"&&(isNaN($scope.attribute.valueExpress)==true||$scope.attribute.valueExpress.match("^-?[0-9]*$")==null)){
                GillionMsg.alert("提示","请输入整型的表达式");
                return;
            }else if($scope.attribute.dataType=="Double"&&(isNaN($scope.attribute.valueExpress)==true||$scope.attribute.valueExpress.match("^[-+]?[0-9]*\.?[0-9]+$")==null)){
                GillionMsg.alert("提示","请输入浮点型的表达式");
                return;
            }else if($scope.attribute.dataType=="Date"&&$scope.attribute.valueExpress.match("^[1-2][0-9][0-9][0-9]-([1][0-2]|0[1-9])-([12][0-9]|3[01]|0[1-9]) ([01][0-9]|[2][0-3]):[0-5][0-9]:[0-5][0-9]?\\d$")==null){
                GillionMsg.alert("提示","请输入时间的表达式");
                return;
            }else if($scope.attribute.dataType=="Boolean"&&$scope.attribute.valueExpress!="true"&&$scope.attribute.valueExpress!="false"){
                GillionMsg.alert("提示","请输入布尔型的表达式");
                return;
            }
            if($scope.attribute.isObjectType=='0'){
                $scope.attribute.dataType='String';
            }else if($scope.attribute.isObjectType=='1'){
                $scope.attribute.dataType='Object';
            }
            businessModelAttributeResource.update($scope.attribute, function (response) {
                if(response.success){
                    GillionMsg.alert('提示', '修改成功！');
                    refresh();
                }
            });

        }
        $scope.delete=function(id){
            GillionMsg.confirm('提示信息', '是否确定删除？', function (r) {
                if (r) {
                    businessModelAttributeResource.delete({id:id}, function (response) {
                        if(response.success){
                            GillionMsg.alert('提示', '删除成功！');
                            angular.element(document).trigger('refresh.details');
                            refresh();
                        }
                    });
                }
            })
        }

        $scope.editAttribute = function (id,name,dataType,valueType,valueExpress,parentId,isMust){
            if(event.target.tagName!="I") {
                $scope.attributeName = "属性详情";
                $scope.rightNone = false;
                $scope.rightManager = true;
                $scope.addOper = false;
                $scope.editOper = true;
                var attribute = {};
                attribute.id = id;
                attribute.name = name;
                attribute.dataType = dataType;
                attribute.valueType = valueType;
                attribute.valueExpress = valueExpress;
                attribute.parentId = parentId;
                attribute.isMust = String(isMust);

                if(valueType=='JDBC'){
                    var valueExpress = JSON.parse(attribute.valueExpress);
                    attribute.sqlName=valueExpress.sqlName;
                    attribute.sqlColumn = valueExpress.sqlColumn
                    attribute.params = [];
                    if (angular.isArray(valueExpress.params)) {
                        angular.forEach(valueExpress.params, function(param){
                            attribute.params.push({
                                value: param
                            })
                        });
                    }
                }else if (valueType == 'RemoteService') {
                    var valueExpress = JSON.parse(attribute.valueExpress);
                    attribute.serviceName = valueExpress.serviceName;
                    attribute.params = [];
                    if (angular.isArray(valueExpress.params)) {
                        angular.forEach(valueExpress.params, function(param){
                            attribute.params.push({
                                value: param
                            })
                        });
                    }
                }else if (valueType == 'Dubbo') {
                    var valueExpress = JSON.parse(attribute.valueExpress);
                    attribute.dubboName = valueExpress.dubboName;
                    attribute.params = [];
                    if (angular.isArray(valueExpress.params)) {
                        angular.forEach(valueExpress.params, function(param){
                            attribute.params.push({
                                value: param
                            })
                        });
                    }
                }else if (valueType == 'SpringCloud') {
                    var valueExpress = JSON.parse(attribute.valueExpress);
                    attribute.springCloudName = valueExpress.springCloudName;
                    attribute.params = [];
                    if (angular.isArray(valueExpress.params)) {
                        angular.forEach(valueExpress.params, function (param) {
                            attribute.params.push({
                                value: param
                            })
                        });
                    }
                } else if (valueType == 'Rule') {
                    var valueExpress = JSON.parse(attribute.valueExpress);
                    attribute.groupId = valueExpress.groupId;
                    attribute.artifactId = valueExpress.artifactId;
                    attribute.params = [];
                    if (angular.isArray(valueExpress.params)) {
                        angular.forEach(valueExpress.params, function(param){
                            attribute.params.push({
                                value: param
                            })
                        });
                    }
                }
                if(dataType=="Object"){
                    attribute.isObjectType = 1;
                }else{
                    attribute.isObjectType = 0;
                }

                $scope.attribute = attribute;
            }
        };


        $scope.viewObject = function (id,margin,name,dataType,valueType,valueExpress,isMust) {
            $scope.rightNone=false;
            $scope.rightManager=true;
            $scope.addOper=false;
            $scope.editOper=true;
            var attribute={};
            attribute.id=id;
            attribute.name=name;
            attribute.dataType=dataType;
            attribute.valueType=valueType;
            attribute.valueExpress=valueExpress;
            attribute.isMust =String(isMust);
            $scope.attribute = attribute;

            if($("#model"+id).text()=="对象[-]"){
                angular.element("#modelSon"+id).text("");
                $("#model"+id).text("对象[+]");
                return;
            }
            if($("#"+id).text()=="对象[-]"){
                angular.element("#modelSon"+id).text("");
                $("#"+id).text("对象[+]");
                return;
            }
            $("#"+id).text("对象[-]");
            $("#model"+id).text("对象[-]");
            childAttributeResource.get({
                id: id
            }, function (response) {
                if (response.success) {
                    var records = response.data;
                    angular.forEach(records, function (item){
                        if(item.dataType!='Object'){
                            angular.element("#modelSon"+id).append(
                                $compile(
                                    "<div class='model-value model-value-border' style='margin-left:"+20*margin+"px'  ng-click='editAttribute(&apos;"+item.id+"&apos;,&apos;"+item.name+"&apos;,&apos;"+item.dataType+"&apos;,&apos;"+item.valueType+"&apos;,&apos;"+item.valueExpress+"&apos;,&apos;"+item.parentId+"&apos;,&apos;"+item.isMust+"&apos;)'>"+
                                    "<div class='model-value-l'><span  class='engine-btn-model' id='"+item.id+"'  >"+item.dataType+"</span></div>"+
                                    "<div class='model-value-r'>"+item.name+"</div>"+
                                    "<div class='model-value-right'>"+
                                    "<span class='results'>"+item.valueExpress+"</span>"+
                                    "<span class='remove'>{{'"+item.valueType+"' | valueTypeFilter}}</span>"+
                                    "</div>"+
                                    "<div class='clear'></div>"+
                                    "</div>"
                                )($scope)
                            )
                        }else{
                            angular.element("#modelSon"+id).append(
                                $compile(
                                    "<div class='model-value  model-value-border' style='margin-left:"+20*margin+"px' ng-click='editAttribute(&apos;"+item.id+"&apos;,&apos;"+item.name+"&apos;,&apos;"+item.dataType+"&apos;,&apos;"+item.valueType+"&apos;,&apos;"+item.valueExpress+"&apos;,&apos;"+item.parentId+"&apos;,&apos;"+item.isMust+"&apos;)' >"+
                                    "<div class='model-value-l'><button type='button' class='engine-btn-model' id='"+item.id+"' ng-click='viewObject(&apos;"+item.id+"&apos;,"+(margin+1)+",&apos;"+item.name+"&apos;,&apos;"+item.dataType+"&apos;,&apos;"+item.valueType+"&apos;,&apos;"+item.valueExpress+"&apos;,&apos;"+item.isMust+"&apos;)' >对象[+]</button></div>"+
                                    "<div class='model-value-r'>"+item.name+"</div>"+
                                    "<div class='model-value-right'>"+
                                    "<span class='results'>"+item.valueExpress+"</span>"+
                                    "<span class='plus'><a href='javascript:void(0)' ng-click='addSon(\""+item.id+"\")'><i class='icon-engine-plus'></i></a></span>"+
                                    "<span class='remove'>{{'"+item.valueType+"' | valueTypeFilter}}</span>"+
                                    "</div>"+
                                    "<div class='clear'></div>"+
                                    " </div>"+
                                    "<div id='modelSon"+item.id+"'></div>"

                                )($scope)
                            )
                        }
                    })
                }
            });
        };

        $scope.addParam = function() {
            if (!$scope.attribute.params) {
                $scope.attribute.params = [];
            }
            $scope.attribute.params.push({
                value:''
            });
        };

        $scope.removeParam = function(index) {
            $scope.attribute.params.splice(index, 1);
        };

         $scope.addFromJson=function(){
             var fd =new FormData();
             var file = document.querySelector('input[type=file]').files[0];
            if(file==undefined){
                GillionMsg.alert('提示', '请选择文件！');
                return;
            }
             fd.append('file', file);
             fd.append('modelId',$scope.businessModelId);
             $http({
                 method:'POST',
                 url:"/grule-manager/businessModelAttribute/addFromJson",
                 data: fd,
                 headers: {'Content-Type':undefined},
                 transformRequest: angular.identity
             }).success( function ( response ) {
                     if(response.success){
                         GillionMsg.alert('提示', '导入成功！');
                         refresh();
                         $scope.detailsShow = true;
                     }
                 });
        }

        $scope.removeAll = function(){
            $scope.businessModelId;
            GillionMsg.confirm('提示信息', '是否确定全部删除？', function (r) {
                if (r) {

                    Resource("/grule-manager/businessModelAttribute/removeAll/:businessModelId", {businessModelId: '@businessModelId'}).delete({
                        businessModelId:  $scope.businessModelId
                    },  function (response) {
                        if(response.success){
                            GillionMsg.alert('提示', '删除成功！');
                            angular.element(document).trigger('refresh.details');
                            refresh();
                        }
                    });
                }
            })
        }
    };
});